/* eslint-disable @typescript-eslint/no-use-before-define */
import { DictValueEnum } from "@/components/DictTag";
import { getPosition } from "@/services/api/module/system/post";
import { ModalForm, ProFormDigit, ProFormInstance, ProFormRadio, ProFormText, ProFormTextArea } from "@ant-design/pro-components";
import React, { useEffect, useRef, useState } from "react";
import { formTitle } from "../constants";
export type PostFormData = Record<string, unknown> & Partial<API.Setting.PostBo>;

export type PostFormProps = {
	onCancel: (flag?: boolean) => void;
	onSubmit: (values: PostFormData) => Promise<any>;
	id: number | undefined;
	open: boolean;
	statusOptions: DictValueEnum;
};
const PositionForm: React.FC<PostFormProps> = props => {
	const formRef = useRef<ProFormInstance>();
	const [title, setTitle] = useState(formTitle[0]);
	const { statusOptions, id, onCancel, onSubmit } = props;
	// 初始化
	useEffect(() => {
		formRef?.current?.resetFields();
		if (id) {
			setTitle(formTitle[1]);
			setFormValue(id);
		}
	}, [id]);
	// 表单赋值
	const setFormValue = (id: number) => {
		getPosition(id).then((data: any) => {
			formRef?.current?.setFieldsValue(data);
		});
	};
	// 关闭
	const handleCancel = () => {
		setTitle(formTitle[0]);
		onCancel();
	};
	// 表单提交
	const handleFinish = async (values: Record<string, any>) => {
		// @ts-ignore
		return onSubmit({
			...(values as PostFormData),
			id: id ? id : undefined
		} as PostFormData);
	};

	return (
		<ModalForm<PostFormData>
			width={620}
			title={title}
			open={props.open}
			formRef={formRef}
			key="id"
			grid={true}
			layout="vertical"
			modalProps={{
				destroyOnClose: true,
				onCancel: () => {
					handleCancel();
				}
			}}
			onFinish={handleFinish}
		>
			<ProFormText
				name="name"
				label="职位名称"
				placeholder="请输入岗位名称"
				rules={[
					{
						required: true,
						message: "请输入岗位名称！"
					}
				]}
			/>
			<ProFormText
				name="code"
				label="职位编码"
				placeholder="请输入岗位编码"
				rules={[
					{
						required: true,
						message: "请输入岗位编码！"
					}
				]}
			/>
			<ProFormDigit
				name="sort"
				label="显示顺序"
				initialValue={0}
				placeholder="请输入显示顺序"
				rules={[
					{
						required: true,
						message: "请输入显示顺序！"
					}
				]}
			/>
			<ProFormRadio.Group
				valueEnum={statusOptions}
				name="status"
				label="状态"
				initialValue={"0"}
				placeholder="请输入状态"
				rules={[
					{
						required: true,
						message: "请输入状态！"
					}
				]}
			/>
			<ProFormTextArea
				name="remark"
				label="备注"
				allowClear
				placeholder="请输入备注"
				rules={[
					{
						required: false,
						message: "请输入备注！"
					}
				]}
			/>
		</ModalForm>
	);
};

export default PositionForm;
